<?php

namespace STAGE\StageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use STAGE\UserBundle\Entity\Tache;
use STAGE\StageBundle\Form\TacheType;
use Symfony\Component\HttpFoundation\Response;


class TacheController extends Controller {

    public function indexAction() {
        return $this->render('StageBundle:Tache:index.html.twig');
    }

    public function newAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
       
         if ($id == '')
             $tache = new Tache();
         else
            $tache = $em->getRepository('UserBundle:Tache')->find($id);
        $form = $this->createForm(new TacheType(), $tache);
        if ($request->isMethod('post')) {
            $form->bind($request);
//            if($form->isValid()){
            $tache = $form->getData();
           
            $tache->setEnabled(true);
            $em->persist($tache);
            $em->flush();
            $url = $this->generateUrl('stage_tache_list');
            return $this->redirect($url);
//            }
        }
        return $this->render('StageBundle:Tache:new.html.twig', array('id' => $id, 'form' => $form->createView()));
    }

    public function listAction() {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $type = $request->get('type');
        $taches = $em->getRepository('UserBundle:Tache')->getTache();
        if ($type != '') {
            return $this->render('StageBundle:Tache:page_list.html.twig', array('taches' => $taches));
        }
        return $this->render('StageBundle:Tache:list.html.twig', array('taches' => $taches));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
        $tache = $em->getRepository('UserBundle:Tache')->find($id);
        $em->remove($tache);
        $em->flush();
        $url = $this->generateUrl('stage_tache_list', array('type' => 'ajax'));
        return $this->redirect($url);
    }

}
